package com.lzh.dlykserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzh.dlykserver.DlykServerApplication;
import com.lzh.dlykserver.constant.Constants;
import com.lzh.dlykserver.entity.TProduct;
import com.lzh.dlykserver.mapper.TProductMapper;
import com.lzh.dlykserver.query.ProductDTO;
import com.lzh.dlykserver.query.ProductQuery;
import com.lzh.dlykserver.result.DicEnum;
import com.lzh.dlykserver.service.ProductService;
import com.lzh.dlykserver.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private TProductMapper tProductMapper;

    @Override
    public List<TProduct> getAllOnSaleProduct() {
        // 强制刷新缓存
        DlykServerApplication.cacheMap.remove(DicEnum.PRODUCT.getCode());
        List<TProduct> tProducts = tProductMapper.selectAllOnSaleProduct();
        DlykServerApplication.cacheMap.put(DicEnum.PRODUCT.getCode(), tProducts);
        return tProducts;
    }

    @Override
    public PageInfo<TProduct> getProducts(Integer current, ProductQuery productQuery) {
        //设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        //查询
        List<TProduct> list = tProductMapper.getProducts(productQuery);
        //封装分页数据到PageInfo
        PageInfo<TProduct> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int addProduct(ProductDTO productDTO) {
        TProduct tProduct = new TProduct();
        BeanUtils.copyProperties(productDTO, tProduct);

        Integer loginID = JWTUtils.parseUserFromJWT(productDTO.getToken()).getId();
        tProduct.setCreateBy(loginID);
        tProduct.setCreateTime(new Date());
        return tProductMapper.insertSelective(tProduct);
    }

    @Override
    public int editProduct(ProductDTO productDTO) {
        TProduct tProduct = new TProduct();
        BeanUtils.copyProperties(productDTO, tProduct);

        Integer loginID = JWTUtils.parseUserFromJWT(productDTO.getToken()).getId();
        tProduct.setEditBy(loginID);
        tProduct.setEditTime(new Date());
        return tProductMapper.updateByPrimaryKeySelective(tProduct);
    }

    @Override
    public TProduct getProductById(Integer id) {
        return tProductMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteProduct(Integer id) {
        return tProductMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int batchDeleteProduct( List<String> idList) {
        return tProductMapper.batchDeleteProduct(idList);
    }


}
